﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Interfleet.SE.UICompiler.Core.Batch
{
    /// <summary>
    /// This class is responsible for persisting batch files.
    /// </summary>
    public class BatchPersistor
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="batchFile">Full path of the batch file</param>
        /// <param name="arguments">Arguments for the compiler</param>
        public BatchPersistor(string batchFile, Arguments arguments)
            : this(batchFile, arguments, new FileProvider())
        {
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="batchFile">Full path of the batch file</param>
        /// <param name="arguments">Arguments for the compiler</param>
        /// <param name="fileProvider">An instance of <see cref="IFileProvider"/></param>
        public BatchPersistor(string batchFile, Arguments arguments, IFileProvider fileProvider)
        {
            if (string.IsNullOrEmpty(batchFile))
            {
                throw new ArgumentNullException("batchFile");
            }
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }
            if (fileProvider == null)
            {
                throw new ArgumentNullException("fileProvider");
            }
            _batchFile = batchFile;
            _arguments = arguments;
            _fileProvider = fileProvider;
            SetupXElement();
        }

        private void SetupXElement()
        {
            _xElement = XElement.Parse("<Batch compileSupplier=\"\" compileOption=\"\" outputFile=\"\"><Files/></Batch>");
            _xElement.Attribute("compileSupplier").Value = _arguments.CompileType.Supplier.ToString();
            _xElement.Attribute("compileOption").Value = _arguments.CompileOption;
            _xElement.Attribute("outputFile").Value = _arguments.CompiledFileName;
            foreach (var file in _arguments.Files)
            {
                _xElement.Descendants("Files").First().Add(new XElement("File", file));
            }
        }

        private string _batchFile;
        private Arguments _arguments;
        private XElement _xElement;
        private IFileProvider _fileProvider;

        /// <summary>
        /// Saves the batch to the batch file path specified in the constructor
        /// </summary>
        /// <returns>true if save operation succeeds</returns>
        public bool CreateBatchFile()
        {
            _fileProvider.SaveToFile(_batchFile, _xElement.ToString());
            return true;
        }
    }
}
